<template>
  <div class="ai-chat-container">
    <!-- 聊天历史区域 -->
    <div class="chat-history">
      <div v-for="(message, index) in chatHistory" :key="index"
        :class="['message-item', message.role === 'user' ? 'user-message' : 'ai-message']">
        <!-- 用户消息显示在右侧，AI消息显示在左侧 -->
        <template v-if="message.role === 'user'">
          <div class="message-content">
            <div class="message-role">{{ message.role === 'user' ? '落地的枫叶' : 'AI助手' }}</div>
            <div class="message-text" v-html="formatMessage(message.content)"></div>
          </div>
          <div class="message-avatar user-avatar">
            <img :src="userAvatar" alt="用户头像">
          </div>
        </template>
        <template v-else>
          <div class="message-avatar ai-avatar">
            <img :src="aiAvatar" alt="AI头像">
          </div>
          <div class="message-content">
            <div class="message-role">
              <span>AI助手</span>
              <!-- 添加复制按钮 -->
              <button class="copy-button" @click="copyMessage(message.content)" title="复制内容">
                <i class="el-icon-document-copy"></i>
              </button>
            </div>
            <div class="message-text" v-html="formatMessage(message.content)"></div>
          </div>
        </template>
      </div>

      <!-- AI思考中的动画 -->
      <div v-if="isThinking" class="message-item ai-message thinking-animation">
        <div class="message-avatar ai-avatar">
          <img :src="aiAvatar" alt="avatar">
        </div>
        <div class="message-content">
          <div class="message-role">AI助手</div>
          <div class="message-text thinking-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>

      <div ref="chatEnd"></div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <div class="input-container">
        <textarea v-model="userInput" placeholder="请输入您的问题..." @keydown.enter.prevent="sendMessage"
          class="chat-textarea" ref="inputArea"></textarea>
        <div class="input-actions">
          <button class="action-button" @click="isTyping ? stopTyping() : sendMessage()"
            :disabled="isProcessing || (!userInput.trim() && !isTyping)" :class="{ 'thinking': isTyping }">
            <img :src="isTyping ? stopIcon : sendIcon" :alt="isTyping ? '停止' : '发送'" class="action-icon">
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import OpenAI from 'openai';  // 添加这行导入语句
export default {
  name: 'HomeView',
  mixins: [],
  components: {},
  props: {},
  data() {
    return {
      userInput: '',
      isProcessing: false,
      isThinking: false, // 新增：AI思考状态
      typingSpeed: 20, // 新增：打字速度(ms)
      userAvatar: require('@/assets/people.png'),
      aiAvatar: require('@/assets/ai.png'),
      chatHistory: [
        {
          role: 'ai',
          content: '您好！我是您的AI助手，有什么可以帮助您的吗？'
        }
      ],
      // 新增：模拟对话数据
      demoResponses: [
        ...require('@/assets/dailyConversations.json').conversations,
        // 保留原有的问答
        {
          question: "什么是HPE GreenLake?",
          answer: "HPE GreenLake是惠普企业(HPE)提供的一种即服务(as-a-service)平台，它将云计算体验带入您的应用程序和数据所在的位置。它提供了一种混合云服务模式，让您可以按需使用和付费，同时保持对环境的控制。HPE GreenLake提供了硬件、软件和专业知识的组合，以简化IT运营并提高业务敏捷性。"
        },
        // 添加新的测试数据
        {
          question: "展示代码块测试",
          answer: "以下是一个Python代码示例：\n```python\ndef hello_hpe():\n    print('Welcome to HPE!')\n    return True\n\n# 调用函数\nresult = hello_hpe()\n```\n\n同时也可以使用行内代码 `print('HPE')` 来展示。"
        },
        {
          question: "展示Markdown格式",
          answer: "# HPE 产品介绍\n\n**HPE** 提供了全面的企业级解决方案，包括：\n\n* 服务器\n* 存储\n* 网络\n\n*了解更多详情*请[访问HPE官网](https://www.hpe.com/)"
        },
        {
          question: "展示表格数据",
          answer: "| 产品ID | 产品名称    | 分类      | 价格 (¥) | 库存数量 | 上架日期    | 评分  |\n|--------|------------|----------|---------|--------|------------|------|\n| 1001   | iPhone 15  | 手机      | 6999    | 120    | 2023-09-20 | 4.8  |\n| 1002   | MacBook Pro 16 | 笔记本电脑 | 18999   | 50     | 2023-07-15 | 4.9  |\n| 1003   | iPad Air   | 平板电脑  | 4799    | 200    | 2023-05-30 | 4.7  |\n| 1004   | Apple Watch 9 | 智能手表  | 3199    | 80     | 2023-10-05 | 4.6  |\n| 1005   | AirPods Pro 2 | 耳机      | 1999    | 300    | 2023-08-10 | 4.5  |\n| 1006   | Dell XPS 13 | 笔记本电脑 | 12999   | 40     | 2023-06-18 | 4.8  |\n| 1007   | Sony WH-1000XM5 | 耳机      | 2999    | 150    | 2023-04-22 | 4.7  |\n| 1008   | 华为 Mate 60 | 手机      | 5999    | 180    | 2023-09-10 | 4.6  |\n| 1009   | 小米 14 Pro  | 手机      | 5299    | 220    | 2023-11-01 | 4.5  |\n| 1010   | ThinkPad X1 Carbon | 笔记本电脑 | 14999   | 35     | 2023-07-08 | 4.9  |"
        },
        {
          question: "混合格式测试",
          answer: "# HPE 技术栈\n\n下面是一个配置示例：\n\n```json\n{\n  \"server\": \"HPE ProLiant DL380\",\n  \"storage\": \"HPE Primera\",\n  \"network\": \"Aruba\"\n}\n```\n\n**重要提示：**\n- 支持 *灵活部署*\n- 提供`24/7`技术支持\n- 完整的[技术文档](https://www.hpe.com/docs)"
        },
        {
          question: "HPE的主要产品线有哪些?",
          answer: "HPE的主要产品线包括：\n1. 计算解决方案：如HPE ProLiant服务器、HPE Synergy和HPE Superdome Flex\n2. 存储解决方案：如HPE Primera、HPE Nimble Storage和HPE 3PAR\n3. 网络解决方案：如HPE Aruba网络产品\n4. 混合云解决方案：如HPE GreenLake\n5. 高性能计算解决方案：如HPE Apollo系统\n6. 边缘计算解决方案：如HPE Edgeline系统\n这些产品线共同构成了HPE的全面企业IT基础设施产品组合。"
        },
        {
          question: "HPE与HP有什么区别?",
          answer: "HPE(惠普企业)与HP(惠普)的区别在于它们是2015年原惠普公司(HP)分拆后形成的两家独立公司：\n\n- HPE(Hewlett Packard Enterprise)：专注于企业级IT基础设施、软件、服务和解决方案，包括服务器、存储、网络设备、云服务等企业IT产品。\n\n- HP Inc.：专注于个人电脑和打印机业务，面向消费者和小型企业，提供笔记本电脑、台式机、打印机等产品。\n\n这两家公司现在有各自独立的管理团队、股票代码和业务战略。"
        }
      ],
      isTyping: false, // 新增：控制打字机效果的状态
      typewriterTimer: null, // 新增：打字机定时器
      currentTypingInterval: null, // 新增：当前打字机定时器，
      sendIcon: require('@/assets/send.svg'),
      stopIcon: require('@/assets/stop.svg'),
    }
  },
  computed: {},
  watch: {
    chatHistory: {
      handler() {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      },
      deep: true
    }
  },
  created() { },
  mounted() {
    this.scrollToBottom();
    // 可选：加载一些演示数据
    this.loadDemoData();
  },
  methods: {
    // 新增：加载演示数据
    loadDemoData() {
      // 如果需要自动加载演示数据，取消下面的注释
      /*
      setTimeout(() => {
        const demoData = this.demoResponses[0];
        this.chatHistory.push({
          role: 'user',
          content: demoData.question
        });
 
        setTimeout(() => {
          this.simulateTypingResponse(demoData.answer);
        }, 1000);
      }, 2000);
      */
    },

    // 新增：模拟打字机效果
    simulateTypingResponse(fullText) {
      this.isThinking = false;
      this.isTyping = true;

      const aiResponseIndex = this.chatHistory.push({
        role: 'ai',
        content: ''
      }) - 1;

      let currentText = '';
      let charIndex = 0;

      const typeNextChar = () => {
        if (charIndex < fullText.length) {
          currentText += fullText.charAt(charIndex);
          this.chatHistory[aiResponseIndex].content = currentText;
          charIndex++;
          this.currentTypingInterval = setTimeout(typeNextChar, this.typingSpeed);
        } else {
          this.isTyping = false;
          this.currentTypingInterval = null;
        }
      };

      typeNextChar();
    },

    // 停止打字方法
    stopTyping() {
      if (this.currentTypingInterval) {
        clearTimeout(this.currentTypingInterval);
        this.currentTypingInterval = null;
      }
      this.isTyping = false;
      this.isThinking = false;
      this.isProcessing = false;
    },

    // 调用 Deepseek 接口的方法
    async callDeepseekAPI(message) {
      try {
        // 思考动画
        this.isThinking = true;

        const openai = new OpenAI({
          baseURL: 'https://api.deepseek.com/v1',
          apiKey: process.env.VUE_APP_DEEPSEEK_API_KEY,
          defaultHeaders: {
            'Content-Type': 'application/json'
          },
          dangerouslyAllowBrowser: true,  // 添加此配置
          stream: true, // 开启流式传输
        });

        const completion = await openai.chat.completions.create({
          messages: [
            {
              role: "system",
              content: "你是一个专业的AI助手。"
            },
            {
              role: "user",
              content: message
            }
          ],
          model: "deepseek-chat",
          max_tokens: 1000,
          temperature: 0.7
        });

        return completion.choices[0].message.content;

      } catch (error) {
        console.error('调用 AI 接口失败:', error);
        // 如果 API 调用失败，返回错误信息
        if (error.response?.status === 402) {
          return '抱歉，AI 服务额度不足，请联系管理员。';
        }
        return '抱歉，服务出现了一些问题，请稍后再试。';
      }
    },

    // ... existing code ...

    // 新增：处理不同格式的模型响应
    processModelResponse(response) {
      // 如果响应为空，返回错误信息
      if (!response) {
        return '抱歉，未收到有效的响应。';
      }

      try {
        // 情况1: 响应已经是字符串
        if (typeof response === 'string') {
          return response;
        }

        // 情况2: 响应是对象，可能有不同的结构
        if (typeof response === 'object') {
          // OpenAI格式: { choices: [{ message: { content: "..." } }] }
          if (response.choices && response.choices.length > 0) {
            if (response.choices[0].message && response.choices[0].message.content) {
              return response.choices[0].message.content;
            } else if (response.choices[0].text) {
              // 某些API可能使用text字段
              return response.choices[0].text;
            }
          }

          // Anthropic Claude格式: { content: [{ text: "..." }] }
          if (response.content && Array.isArray(response.content)) {
            const textParts = response.content
              .filter(item => item.type === 'text' && item.text)
              .map(item => item.text);
            if (textParts.length > 0) {
              return textParts.join('\n');
            }
          }

          // 简单格式: { text: "..." } 或 { content: "..." } 或 { answer: "..." }
          if (response.text) {
            return response.text;
          } else if (response.content && typeof response.content === 'string') {
            return response.content;
          } else if (response.answer) {
            return response.answer;
          } else if (response.response) {
            return response.response;
          }

          // 如果是数组，尝试连接所有文本
          if (Array.isArray(response)) {
            return response.map(item =>
              typeof item === 'string' ? item :
                (item.text || item.content || JSON.stringify(item))
            ).join('\n');
          }

          // 最后尝试将整个对象转为字符串
          return JSON.stringify(response, null, 2);
        }

        // 情况3: 其他类型，转为字符串
        return String(response);
      } catch (error) {
        console.error('处理模型响应时出错:', error);
        return '抱歉，处理响应时出现了问题。';
      }
    },

    // 新增：增强的消息格式化方法，支持代码块和Markdown
    formatMessage(text) {
      if (!text) return '';

      // 处理表格
      text = text.replace(/\|([^\n]+)\|\n\|[-\s|]+\|\n((?:\|[^\n]+\|\n?)+)/g, (match) => {
        const rows = match.split('\n').filter(row => row.trim() && row.includes('|'));
        if (rows.length < 2) return match;

        let tableHtml = '<table class="markdown-table"><tbody>';

        rows.forEach((row, index) => {
          if (index === 1) return; // 跳过分隔行
          const cells = row.split('|').filter(cell => cell.trim());

          tableHtml += '<tr>';
          cells.forEach(cell => {
            const tag = index === 0 ? 'th' : 'td';
            tableHtml += `<${tag} style="border: 1px solid #e8e8e8; padding: 8px;">${cell.trim()}</${tag}>`;
          });
          tableHtml += '</tr>';
        });

        tableHtml += '</tbody></table>';
        return tableHtml;
      });

      // 其他现有的处理逻辑保持不变
      text = text.replace(/```([\s\S]*?)```/g, (match, code) => {
        return `<div class="code-block"><pre>${this.escapeHtml(code)}</pre></div>`;
      });

      // 处理行内代码 (`code`)
      text = text.replace(/`([^`]+)`/g, '<code>$1</code>');

      // 处理粗体 (**text**)
      text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');

      // 处理斜体 (*text*)
      text = text.replace(/\*([^*]+)\*/g, '<em>$1</em>');

      // 处理链接 [text](url)
      text = text.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank">$1</a>');

      // 处理换行
      text = text.replace(/\n/g, '<br>');

      return text;
    },

    // 新增：HTML转义函数，防止XSS攻击
    escapeHtml(unsafe) {
      return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    },

    // 获取模拟回复
    getDemoResponse(message) {
      // 尝试匹配问题，如果没有匹配项则返回默认回复
      const lowerMessage = message.toLowerCase();

      for (const demo of this.demoResponses) {
        if (lowerMessage.includes(demo.question.toLowerCase().substring(0, 5))) {
          return demo.answer;
        }
      }

      // 默认回复
      return "感谢您的提问。我是HPE的AI助手，可以回答关于HPE产品、服务和解决方案的问题。请问您想了解哪方面的信息呢？";
    },

    async sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isProcessing) return;

      // 添加用户消息到聊天历史
      this.chatHistory.push({
        role: 'user',
        content: message
      });

      this.userInput = '';
      this.isProcessing = true;

      try {
        // 调用 Deepseek API 获取回复内容
        const aiResponse = await this.callDeepseekAPI(message);

        // 使用打字机效果显示回复
        this.simulateTypingResponse(aiResponse);
      } catch (error) {
        // 发生错误时显示错误消息
        this.isThinking = false;
        this.chatHistory.push({
          role: 'ai',
          content: '抱歉，服务出现了一些问题，请稍后再试。'
        });
        console.error('发送消息时出错:', error);
      } finally {
        this.isProcessing = false;
      }
    },

    scrollToBottom() {
      if (this.$refs.chatEnd) {
        this.$refs.chatEnd.scrollIntoView({ behavior: 'smooth' });
      }
    },
    copyMessage(text) {
      // 创建一个临时textarea元素
      const textarea = document.createElement('textarea');
      // 移除HTML标签和转义字符，保留换行
      const plainText = text
        .replace(/<br\s*\/?>/g, '\n')  // 将<br>转换为换行符
        .replace(/<[^>]+>/g, '')       // 移除其他HTML标签
        .replace(/&nbsp;/g, ' ')       // 转换空格
        .replace(/&lt;/g, '<')         // 转换<
        .replace(/&gt;/g, '>')         // 转换>
        .replace(/&amp;/g, '&')        // 转换&
        .replace(/&quot;/g, '"')       // 转换"
        .replace(/&#039;/g, "'");      // 转换'

      textarea.value = plainText;
      textarea.style.position = 'fixed';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();

      try {
        document.execCommand('copy');
        this.$message({
          message: '复制成功',
          type: 'success',
          duration: 2000
        });
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
        console.error('复制失败:', err);
      } finally {
        document.body.removeChild(textarea);
      }
    }
  }
}
</script>

<style scoped lang="scss">
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  max-width: 900px;
  width: 85%;
  margin: 40px auto;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  overflow: hidden;
  transition: all 0.3s ease;

  .chat-history {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    background-image: linear-gradient(to bottom, rgba(240, 249, 255, 0.2), rgba(240, 249, 255, 0.6));

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;
    }

    .message-item {
      display: flex;
      margin-bottom: 24px;
      animation: fadeIn 0.3s ease;

      .message-avatar {
        width: 44px;
        height: 44px;
        margin-right: 14px;
        flex-shrink: 0;
        position: relative; // 添加相对定位
        border-radius: 50%;
        background-color: #f0f0f0; // 添加背景色
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden; // 确保内容不溢出

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          border: 2px solid #ffffff;
          transition: all 0.3s ease; // 添加过渡效果
        }

        // 用户头像特殊效果
        &.user-avatar::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-radius: 50%;
          box-shadow: inset 0 0 0 1px rgba(24, 144, 255, 0.3);
          z-index: 1;
        }

        // AI头像特殊效果
        &.ai-avatar::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          border-radius: 50%;
          box-shadow: inset 0 0 0 1px rgba(82, 196, 26, 0.3);
          z-index: 1;
        }
      }

      .message-content {
        max-width: 60%;

        .message-role {
          font-weight: bold;
          margin-bottom: 6px;
          font-size: 14px;
        }

        .message-text {
          padding: 14px 18px;
          border-radius: 18px;
          line-height: 1.6;
          word-break: break-word;
          box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
          font-size: 15px;
        }
      }

      &.user-message {
        justify-content: flex-end;

        .message-avatar {
          margin-right: 0;
          margin-left: 14px;
        }

        .message-content {
          max-width: 66.7%;

          .message-role {
            color: #1890ff;
            text-align: right;
          }

          .message-text {
            background-color: #e6f7ff;
            border: none;
            background-image: linear-gradient(135deg, #e6f7ff, #bae7ff);
            color: #0050b3;
            border-top-right-radius: 4px;
          }
        }
      }

      &.ai-message {
        justify-content: flex-start;

        .message-content {
          max-width: calc(100% - 58px);

          .message-role {
            color: #52c41a;
          }

          .message-text {
            background-color: #f6ffed;
            border: none;
            background-image: linear-gradient(135deg, #f6ffed, #d9f7be);
            color: #135200;
            border-top-left-radius: 4px;
          }
        }
      }

      &.thinking-animation {
        .thinking-dots {
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 24px;
          min-width: 60px;

          span {
            display: inline-block;
            width: 8px;
            height: 8px;
            margin: 0 4px;
            background-color: #52c41a;
            border-radius: 50%;
            opacity: 0.6;
            animation: thinking 1.4s infinite ease-in-out both;

            &:nth-child(1) {
              animation-delay: -0.32s;
            }

            &:nth-child(2) {
              animation-delay: -0.16s;
            }

            &:nth-child(3) {
              animation-delay: 0s;
            }
          }
        }
      }
    }
  }

  .chat-input-area {
    padding: 18px 20px;
    border-top: 1px solid #f0f0f0; // 更淡的分隔线
    background-color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03); // 添加上阴影

    .input-container {
      position: relative;

      .chat-textarea {
        width: 96%;
        min-height: 80px;
        padding: 14px;
        border: 1px solid #e8e8e8;
        border-radius: 8px; // 增加圆角
        resize: none;
        font-size: 15px;
        line-height: 1.6;
        transition: all 0.3s ease;

        &:focus {
          outline: none;
          border-color: #40a9ff;
          box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.15);
        }
      }

      .input-actions {
        display: flex;
        justify-content: flex-end;
        margin-top: 10px;

        .action-button {
          width: 46px;
          height: 46px;
          border-radius: 50%;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          background-color: #8c8c8c;
          color: white;
          position: relative;
          overflow: hidden;

          i {
            font-size: 20px;
            transition: all 0.3s ease;
          }

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);

            &::before {
              transform: translate(-50%, -50%) scale(1);
              opacity: 0;
            }
          }

          &::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 100%;
            height: 100%;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            transform: translate(-50%, -50%) scale(0);
            opacity: 1;
            transition: transform 0.6s ease, opacity 0.6s ease;
          }

          &:active {
            transform: translateY(0);
          }

          &:disabled {
            background-color: #d9d9d9;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
          }

          .action-icon {
            width: 24px;
            height: 24px;
            transition: all 0.3s ease;
          }

          &.thinking {
            background-color: #8c8c8c;

            &:hover {
              background-color: #595959;
            }

            .action-icon {
              transform: scale(1.1);
            }
          }
        }
      }
    }
  }
}

// 添加思考动画关键帧
@keyframes thinking {

  0%,
  80%,
  100% {
    transform: scale(0.6);
    opacity: 0.4;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}

// 添加动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message-text {
  // ... 现有样式 ...

  .markdown-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    margin: 12px 0;
    background-color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border: 1px solid #e8e8e8;
      transition: all 0.3s ease;
    }

    th {
      background: linear-gradient(to bottom, #f8fafd, #f0f5ff);
      font-weight: 600;
      color: #1f1f1f;
      border-bottom: 2px solid #1890ff;
      text-shadow: 0 1px 0 #fff;
      position: relative;

      &:not(:last-child)::after {
        content: '';
        position: absolute;
        right: 0;
        top: 20%;
        height: 60%;
        width: 1px;
        background-color: rgba(24, 144, 255, 0.2);
      }
    }

    td {
      color: #595959;
      background-color: #ffffff;
      border: 1px solid #e8e8e8;
    }

    tr {
      &:nth-child(even) td {
        background-color: #fafafa;
      }

      &:hover td {
        background-color: #f0f7ff;
      }
    }
  }
}

.message-role {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;

  .copy-button {
    opacity: 0;
    padding: 6px 8px;
    border: none;
    background: rgba(0, 0, 0, 0.04);
    cursor: pointer;
    color: #8c8c8c;
    border-radius: 4px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 4px;

    &:hover {
      background-color: rgba(24, 144, 255, 0.1);
      color: #1890ff;
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }

    i {
      font-size: 14px;
    }

    &::after {
      content: '复制';
      font-size: 12px;
    }
  }
}

// 鼠标悬停在消息上时显示复制按钮
.message-item:hover {
  .copy-button {
    opacity: 1;
  }
}
</style>